package user

import (
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/passenger"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/app"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/database"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/paginator"

	"github.com/gofiber/fiber/v2"
)

func Get(id uint64) (user User) {
	database.DB.Where("id", id).First(&user)
	return
}

func GetWithDriverAndPassenger(id uint64) (user User) {
	database.DB.Preload("Driver").Preload("Passenger").Where("id", id).First(&user)
	return
}

func GetBy(field, value string) (user User) {
	database.DB.Where("? = ?", field, value).First(&user)
	return
}

func All() (users []User) {
	database.DB.Order("id desc").Find(&users)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(User{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func IsEmailExist(email string) bool {
	var count int64
	database.DB.Model(User{}).Where("email = ?", email).Count(&count)
	return count > 0
}

func IsPhoneExist(phone string) bool {
	var count int64
	database.DB.Model(User{}).Where("phone = ?", phone).Count(&count)

	return count > 0
}

func IsOpenidExist(openid string) bool {
	var count int64

	database.DB.Model(User{}).Where("open_id = ?", openid).Count(&count)

	return count > 0
}

func CreateUserIfNotExistByOpenid(openid string) User {

	if !IsOpenidExist(openid) {
		userModel := User{
			OpenId: openid,
		}
		database.DB.Create(&userModel)

		passengerModel := passenger.Passenger{
			UserId: userModel.ID,
		}

		// 注册乘客信息
		passengerModel.Create()

		return userModel
	}
	userModel := User{}
	database.DB.Model(User{}).Where("open_id = ?", openid).Order("id DESC").First(&userModel)
	return userModel
}

// Paginate 分页内容
func Paginate(c *fiber.Ctx, perPage int) (users []User, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(User{}),
		&users,
		app.V1URL(database.TableName(&User{})),
		perPage,
	)
	return
}
